<template>
    <el-form ref="formRef" :model="formData" :inline="true" class="common-search-form">
        <el-form-item prop="customerId">
            <SelectRemote
                ref="selectRemote1"
                label="投放主体"
                :target-data="formData.customerId"
                @onChange="(val: any) => onChange(val, 'customerId')"
            />
        </el-form-item>
        <el-form-item prop="company">
            <SelectRemote
                ref="selectRemote2"
                label="签约主体"
                :target-data="formData.company"
                :basic-info="{ value: 'company' }"
                @onChange="(val: any) => onChange(val, 'company')"
            />
        </el-form-item>
        <el-form-item prop="companyProperty">
            <el-select
                v-model="formData.companyProperty"
                clearable
                placeholder="请选择"
                class="select"
                @change="(val: any) => onChange(val, 'companyProperty')"
            >
                <template #prefix>
                    <div class="label">客户类型</div>
                </template>
                <el-option
                    v-for="(item, index) in companyPropertyList"
                    :key="index"
                    :label="item.name"
                    :value="item.code"
                />
            </el-select>
        </el-form-item>
        <el-form-item prop="applyCode">
            <el-select
                v-model="formData.signTypes"
                multiple
                collapse-tags
                placeholder="请选择"
                class="select"
                @change="(val: any) => onChange(val, 'signTypes')"
            >
                <template #prefix>
                    <span class="label">签约类型</span>
                </template>
                <el-option label="全部" value="all"></el-option>
                <el-option
                    v-for="item in signTypeList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                    :disabled="formData.signTypes.includes('all')"
                />
            </el-select>
        </el-form-item>
        <el-form-item prop="applyCode">
            <el-input
                v-model="formData.applyCode"
                clearable
                placeholder="请输入"
                class="form-input select"
                @change="(val: any) => onChange(val, 'applyCode')"
            >
                <template #prefix>
                    <span class="label">签约编码</span>
                </template>
            </el-input>
        </el-form-item>
        <el-form-item prop="industry">
            <el-select
                v-model="formData.industry"
                clearable
                placeholder="请选择"
                class="select"
                @change="(val: any) => onChange(val, 'industry')"
            >
                <template #prefix>
                    <div class="label">客户行业</div>
                </template>
                <el-option v-for="(item, index) in industryList" :key="index" :label="item.name" :value="item.code" />
            </el-select>
        </el-form-item>
        <el-form-item prop="brandName">
            <el-input
                v-model="formData.brandName"
                clearable
                placeholder="请输入"
                class="form-input select"
                @change="(val: any) => onChange(val, 'brandName')"
            >
                <template #prefix>
                    <span class="label">品牌名称</span>
                </template>
            </el-input>
        </el-form-item>
        <el-form-item prop="approveStatus">
            <el-select
                v-model="formData.approveStatus"
                multiple
                collapse-tags
                clearable
                placeholder="请选择"
                class="select"
                @change="(val: any) => onChange(val, 'approveStatus')"
            >
                <template #prefix>
                    <div class="label">审批进度</div>
                </template>
                <el-option label="全选" value=""></el-option>
                <el-option
                    v-for="item in ApprovalStatusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </el-form-item>
        <el-form-item prop="salesId">
            <SelectRemote
                ref="selectRemote3"
                label="销售姓名"
                :target-data="formData.salesId"
                query-type="2"
                :basic-info="{ value: 'userId', label: 'userName' }"
                @onChange="(val: any) => onChange(val, 'salesId')"
            />
        </el-form-item>
        <el-form-item prop="applyCode">
            <el-date-picker
                v-model="planPlayTimeBegin"
                class="date-start"
                type="daterange"
                range-separator="至"
                start-placeholder="请选择"
                end-placeholder="请选择"
                @change="(val: any) => onChange(val, 'planPlayTimeBegin')"
            />
        </el-form-item>
        <el-form-item prop="applyCode">
            <el-date-picker
                v-model="planPlayTimeEnd"
                class="date-end"
                type="daterange"
                range-separator="至"
                start-placeholder="请选择"
                end-placeholder="请选择"
                @change="(val: any) => onChange(val, 'planPlayTimeEnd')"
            />
        </el-form-item>
        <el-form-item>
            <el-button @click="resetForm"> 重置 </el-button>
            <el-button :loading="btnLoading" @click="handleExport">导出</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, defineEmits, onBeforeUnmount } from 'vue';
import { FormData } from '../ModelDefines';
import { ApprovalStatusList } from '@/utils/config';
import SelectRemote from './selectRemote.vue';
import { findAllDictyType, exportApproval, getIndustryFirstList } from '@/api/delivery/customerManage';

const formRef = ref<any>(null);
const selectRemote1 = ref<any>(null);
const selectRemote2 = ref<any>(null);
const selectRemote3 = ref<any>(null);

const btnLoading = ref(false);
const companyPropertyList = ref<any>([]);
const industryList = ref<any>([]);
const signTypeList = ref<any>([]);
const formData = reactive(FormData);
const planPlayTimeBegin = ref([]);
const planPlayTimeEnd = ref([]);

const emit = defineEmits(['searchChange']);

const onChange = (val: string, key: string) => {
    if ((key === 'customerId' || key === 'company' || key === 'salesId') && !val) {
        return;
    }
    if (key === 'planPlayTimeBegin') {
        formData['planPlayTimeBeginFrom'] = val[0];
        formData['planPlayTimeBeginTo'] = val[1];
        emit('searchChange', formData);
        return;
    }
    if (key === 'planPlayTimeEnd') {
        formData['planPlayTimeEndFrom'] = val[0];
        formData['planPlayTimeEndTo'] = val[1];
        emit('searchChange', formData);
        return;
    }
    formData[key] = val;
    if (key === 'signTypes' && val.includes('all')) {
        formData['signTypes'] = ['all'];
    }
    emit('searchChange', formData);
};

const resetForm = () => {
    formRef.value?.resetFields();
    formData.customerId = '';
    formData.company = '';
    formData.salesId = '';
    planPlayTimeBegin.value = [];
    planPlayTimeEnd.value = [];
    formData['planPlayTimeBeginFrom'] = '';
    formData['planPlayTimeBeginTo'] = '';
    formData['planPlayTimeEndFrom'] = '';
    formData['planPlayTimeEndTo'] = '';
    formData['signTypes'] = [];
    selectRemote1.value.onClear();
    selectRemote2.value.onClear();
    selectRemote3.value.onClear();
    emit('searchChange', formData, { pageNum: 1 });
};

const handleExport = async () => {
    btnLoading.value = true;
    try {
        const data = await exportApproval(formData);
        let aDom = document.createElement('a');
        aDom.style.display = 'none';
        aDom.href = data.fileUrl;
        aDom.target = '_blank';
        aDom.setAttribute('download', data.desc || '');
        document.body.appendChild(aDom);
        aDom.click();
        document.body.removeChild(aDom);
    } catch (error) {
        console.log(error);
    } finally {
        btnLoading.value = false;
    }
};

onBeforeUnmount(() => {
    resetForm();
});

onMounted(async () => {
    try {
        const data: any = await Promise.allSettled([findAllDictyType(), getIndustryFirstList()]);
        if (data[0].status === 'fulfilled') {
            companyPropertyList.value = data[0].value?.find(
                (item: any) => item.dictionaryTypeCode === 'company_property'
            )?.dictDetail;
            signTypeList.value = data[0].value
                ?.find((item: any) => item.dictionaryTypeCode === 'business-opportunity-type')
                ?.dictDetail.filter(
                    (item: any) =>
                        item.code !== 'dic-business-opportunity-type-007'
                        && item.code !== 'dic-business-opportunity-type-002'
                );
        }

        if (data[1].status === 'fulfilled') {
            industryList.value = data[1].value;
        }
    } catch (error) {
        console.log(error);
    }
});
</script>

<style lang="scss" scoped>
::v-deep(.el-date-editor) {
    width: 580px;
    .el-input__icon {
        display: none;
    }

    &.date-start::before {
        content: '预计投放开始时间';
        font-size: 14px;
        color: #808080;
        width: 130px;
    }
    &.date-end::before {
        content: '预计投放结束时间';
        font-size: 14px;
        color: #808080;
        width: 130px;
    }
    .el-input__inner {
        padding-left: 96px;
    }
}
</style>
